<template>
  <el-dialog
    v-dialogDrag
    :visible.sync="isViewPopWindows"
    :title="textMap[popupsState]"
    width="70%"
    :append-to-body="true"
    :close-on-click-modal="false"
    @close="close"
    @opened="open"
  >
    <dialogHeader
      slot="title"
      :title="textMap[popupsState]"
      :style-type="$store.state.app.dialogType"
    />
    <div class="formBoxContain">
      <!--
            buttons: 按钮
            froms: 表单
            fromsField: 表单对应的字段
            tableOption: 网格项
            dynamicApiConfigs: 取值
         -->

      <one-table-template
        ref="multipleTable"
        :dynamic-buttons="tableButtons"
        :dynamic-components="tableComponents"
        :dynamic-form-fields="formField"
        :dynamic-table-cols="tableCols"
        :dynamic-table-defult-height="350"
        :dynamic-is-show-select="true"
        :dynamic-is-show-more-btn="true"
        :dynamic-is-init-table="false"
        :is-show-pagination="false"
        :callback-obj="callbackObj"
      >
        <template #saleQty="scope">
<!--          <el-input-->
<!--            v-model="scope.row['saleQty']"-->
<!--            placeholder="申请数量"-->
<!--            @input="saleQtyChange($event, scope)"-->
<!--          />-->
          <el-input-number
            :key="'qty' + scope.$index"
            v-model="scope.row['saleQty']"
            :step="1"
            :min="0"
            :max="scope.row['theoryUsableStorage']"
            step-strictly
          />
        </template>
      </one-table-template>

      <Add
        :is-view-pop-windows-add="isViewPopWindowsAdd"
        :dynamic-edit-row-data="editRowData"
        :chosen-list="chosenList"
        @close="closed"
        @selectiondata="selectiondata1"
      />
    </div>
  </el-dialog>
</template>

<script>
import dialogHeader from '@/components/dialogHeader'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/vehicleManagement'
import { vehiclePdiPriceInquirys } from '@/api/se/vehiclePdiPriceInquiry'
import { exportExcel } from '@/utils/getTimeString.js'
import { formMixins } from '@/components/mixins/formMixins'

export default {
  components: {
    dialogHeader,
    OneTableTemplate,
    Add: () => import('./add')
  },
  // 组件混入对象
  mixins: [formMixins],
  props: {
    // 是否关闭弹窗
    isViewPopWindows: {
      type: Boolean,
      default: false
    },
    dynamicEditRowData: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      chosenList: [],
      dynamicApiConfigs: '',
      isViewPopWindowsAdd: false,
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '申请单号:',
              codeField: 'applyOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',

              isMust: true,
              disabled: true,
              span: 6
            },
            {
              compKey: 'compKey2',
              labelName: '出库类型:',
              codeField: 'outboundType',
              textField: 'outboundTypeCn',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              type: 'dropdownList',
              options: [
                { statusId: '4', statusText: '领用出库' },
                { statusId: '6', statusText: '报废出库' }
              ],
              isRequire: true,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey3',
              labelName: '领用去向：',
              codeField: 'applyDept',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              span: 6,
              isRequire: true
            },
            {
              compKey: 'compKey4',
              labelName: '成本中心:',
              codeField: 'costCentre',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 6,
              isRequire: true
            },
            {
              compKey: 'compKey5',
              labelName: '申请人：',
              codeField: 'applyPerson',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'compKey6',
              labelName: '出库用途：',
              codeField: 'applyUse',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'compKey7',
              labelName: '收货人:',
              codeField: 'receivePerson',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 6,
              isRequire: true
            },
            {
              compKey: 'compKey8',
              labelName: '联系电话:',
              codeField: 'linkPhone',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 6,
              isRequire: true,
              validrule: {
                isPhone: true,
                maxlength: 11
              }
            },

            {
              compKey: 'compKey9',
              labelName: '收货地址:',
              codeField: 'receiveAddress',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 12,
              isRequire: true
            },
            {
              compKey: 'compKey5',
              labelName: '出库仓库：',
              codeField: 'warehouseName',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'warehouseName,warehouseName',
              customObj: {
                api: {
                  APIUrl: '/mp/e3sh/spareparts/nodestorehouse/checkWarehousingService/queryWarehouseName.do'
                },
                listQuery: {},
                selectType: '1'
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true,
              isRequire: true
            }
          ],
      formField: this.$utils.getFormField(this, {
        applyOrderCode: '',
        outboundType: '',
        outboundTypeCn: '',
        applyDept: '',
        costCentre: '',
        applyPerson: '',
        applyUse: '',
        receivePerson: '',
        linkPhone: '',
        receiveAddress: '',
        warehouseName: ''
      }),
      // 标题
      textMap: {
        edit: '查看出库编辑',
        add: '查看出库新增',
        look: '查看出库明细'
      },
      selectiondata: [],
      // 回调方法对象
      callbackObj: {
        // 网格点击回调事件
        onRowClick: (currentRow) => {
          // this.onRightRowClick(currentRow);
        },
        // 手动勾选网格时，拿到勾选网格的数据
        onCheckSelect: (selection, row) => {
          this.selectiondata = selection
        },
        onCheckSelectChange: (selection) => {
          // this.onCheckSelectChange1(selection)
        }
      },

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'button1',
          type: 'primary',
          size: 'small',
          name: '',
          clickEvent: (index) => {
            // console.log('asd', index);
            this.chosenList = this.$refs['multipleTable'].list.map(o => o['partId'])
            this.isViewPopWindowsAdd = true
            this.editRowData = this.$utils.deepCopy(
              this.$refs['multipleTable'].list[index]
            )
          },
          text: '备件选择',
          position: 'left',
          isShow: true
        },
        {
          compKey: 'button2',
          type: 'primary',
          size: 'small',
          name: '',
          clickEvent: () => this.del(),
          text: '备件删除',
          position: 'left',
          isShow: true
        },
        {
          compKey: 'button3',
          type: 'primary',
          size: 'small',
          name: '',
          // clickEvent: () => this.pass(),
          text: '批量导入',
          position: 'left',
          isShow: true
        },
        {
          compKey: 'button4',
          type: 'primary',
          size: 'small',
          name: '',
          clickEvent: () => this.preserve(),
          text: '保存',
          position: 'right',
          isShow: true
        },
        {
          compKey: 'button5',
          type: 'primary',
          size: 'small',
          name: '',
          clickEvent: () => {
            for (const attr in this.formField) {
              if (attr !== 'applyOrderCode') {
                this.formField[attr] = ''
              }
            }
          },
          text: '重置',
          position: 'right',
          isShow: true
        }
      ],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'partNo',
              label: '备件编码',
              align: 'center'
            },
            {
              prop: 'partName',
              label: '备件名称',
              align: 'center'
            },
            {
              prop: 'storageLocation',
              label: '仓位编码',
              align: 'center'
            },
            {
              prop: 'unit',
              label: '备件单位',
              align: 'center'
            },
            {
              prop: 'theoryUsableStorage',
              label: '理论可用库存',
              align: 'center'
            },
            {
              prop: 'saleQty',
              label: '申请数量+',
              align: 'center',
              isSlot: true
            }
          ]
    }
  },
  methods: {
    saleQtyChange(val, scope) {
      if (!val) return this.$message('数量不能为空!')
      const reg = /c|(^[0-9]+$)/
      if (!reg.test(val)) {
        this.$message('请输入正确的数量!')
        scope.row['saleQty'] = ''
      }
    },
    /**
     * @description 关闭弹窗
     * @time 2021、01、22
     */
    close() {
      this.$emit('close')
      this.isViewPopWindowsAdd = false
    },
    closed() {
      this.isViewPopWindowsAdd = false
    },
    open() {
      if (this.popupsState == 'edit') {
        this.tableButtons[0].isShow = true
        this.tableButtons[1].isShow = true
        this.tableButtons[2].isShow = true
        this.tableButtons[3].isShow = true
        this.tableButtons[4].isShow = true
      }
      if (this.popupsState == 'edit' || this.popupsState == 'look') {
        // this.formField = this.dynamicEditRowData;
        this.formField.applyOrderCode = this.dynamicEditRowData.applyOrderCode
        this.formField.outboundTypeCn = this.dynamicEditRowData.outboundTypeCn
        this.formField.outboundType = this.dynamicEditRowData.outboundType
        this.formField.applyDept = this.dynamicEditRowData.applyDept
        this.formField.costCentre = this.dynamicEditRowData.costCentre
        this.formField.applyPerson = this.dynamicEditRowData.applyPerson
        this.formField.applyUse = this.dynamicEditRowData.applyUse
        this.formField.receivePerson = this.dynamicEditRowData.receivePerson
        this.formField.linkPhone = this.dynamicEditRowData.linkPhone
        this.formField.receiveAddress = this.dynamicEditRowData.receiveAddress
        this.formField.warehouseName = this.dynamicEditRowData.warehouseName
        const queryObj = {
          // 保存mutation
          type: 'mutation',
          // api配置
          apiConfig: vehiclePdiPriceInquirys.findAuditOtherOutboundD,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: {
            applyOrderId: this.dynamicEditRowData.applyOrderId
          }
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        // 调用中台API方法（可复用）
        this.$requestAPI(paramD).then((response) => {
          this.$refs.multipleTable.list = response.rows
        })
      }
      if (this.popupsState == 'look') {
        this.tableButtons[0].isShow = false
        this.tableButtons[1].isShow = false
        this.tableButtons[2].isShow = false
        this.tableButtons[3].isShow = false
        this.tableButtons[4].isShow = false
      }
    },
    // 删除
    del() {
      this.selectiondata.forEach((element) => {
        this.$refs['multipleTable'].list.forEach((item) => {
          if (element == item) {
            this.$refs['multipleTable'].list.splice(item, 1)
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1000
            })
          }
        })
      })
    },
    // 备件选择
    selectiondata1(selectiondata) {
      if (this.$refs['multipleTable'].list.length != 0) {
        selectiondata.forEach((element) => {
          if (this.$refs['multipleTable'].list.indexOf(element) == -1) {
            this.$refs['multipleTable'].list.push(element)
          }
        })
      } else {
        selectiondata.forEach((element) => {
          this.$refs['multipleTable'].list.push(element)
        })
      }
    },
    // 保存
    preserve() {
      this.$utils.validataMoth(this, 'validpage')
      if (!this.valid) return
      let isValid = true
      this.$refs['multipleTable'].list.every(row => {
        if (!row['saleQty']) {
          isValid = false
          return false
        }
        return true
      })
      if (!isValid) return this.$message('网格中[ 申请数量+ ]为必填！')
      // 如果有必填项没有填，这两行代码就会拦截 不往下执行代码
      const that = this
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: vehiclePdiPriceInquirys.saveOtherOutbound,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          ...this.formField,
          applyOrderId: this.dynamicEditRowData.applyOrderId,
          otherOutboundDList: this.$refs['multipleTable'].list
        }
      }
      if (this.popupsState == 'add') {
        queryObj.variables.applyOrderId = ''
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
          this.open()
          this.isViewPopWindows = false
        } else {
          // 保存失败
          this.$message({
            message: '保存失败',
            type: 'warn',
            uration: 2000
          })
        }
      })
    }
  }
}
</script>
<style scoped>
/*.formBoxContain {*/
/*  height: 600px;*/
/*}*/
</style>
